/**
 * 
 */
package com.jushu.storbox.database;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;

import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.entities.FileInfo;
import com.jushu.storbox.util.LogUtil;
import com.huawei.sharedrive.sdk.android.modelV2.response.FileInfoResponseV2;

public class ShareFileDao extends BaseDao implements IShareFileDao {

	public final static String TABLE_NAME = "tb_shard_file_list";
	
	public final static String LOG_TAG = "ShareFileDao";

	/**
	 * 
	 */
	public ShareFileDao() {
	}

	@Override
	public long insertFile(FileInfoResponseV2 fileInfo) {
		long row = -1;
		try {
			ContentValues cv = new ContentValues();
			cv.put(IBaseDao.id, fileInfo.getId());
			cv.put(IBaseDao.file_name, fileInfo.getName());
			cv.put(IBaseDao.is_file, 1);
			cv.put(IBaseDao.owner_by, fileInfo.getOwnerBy());
			cv.put(IBaseDao.parent_folder_id, fileInfo.getParent());
			cv.put(IBaseDao.file_md5, fileInfo.getMd5());
			cv.put(IBaseDao.file_size, fileInfo.getSize());
			cv.put(IBaseDao.server_ctime, fileInfo.getCreatedAt());
			cv.put(IBaseDao.server_mtime, fileInfo.getModifiedAt());
			cv.put(IBaseDao.local_path, "");
			cv.put(IBaseDao.client_ctime, fileInfo.getContentCreatedAt());
			cv.put(IBaseDao.client_mtime, fileInfo.getContentModifiedAt());
			cv.put(IBaseDao.static_status, fileInfo.getStatus());
			cv.put(IBaseDao.trans_status, 0);
			cv.put(IBaseDao.trans_status_ref_cnt, 0);
			cv.put(IBaseDao.is_exist, 0);
			cv.put(IBaseDao.file_true_md5, "");
			cv.put(IBaseDao.local_operation_time, Calendar.getInstance().getTimeInMillis());
			cv.put(IBaseDao.local_last_modify_time, Calendar.getInstance().getTimeInMillis());
			cv.put(IBaseDao.file_sha1, fileInfo.getSha1());
			cv.put(IBaseDao.isencrypt, fileInfo.isEncrypt());
			cv.put(IBaseDao.isshare, fileInfo.isShare());
			cv.put(IBaseDao.isshare_link, fileInfo.isSharelink());
			cv.put(IBaseDao.isSync, 0);
			cv.put(IBaseDao.fileIcon, fileInfo.getThumbnailURL());
			row = this.getDb().insert(TABLE_NAME, null, cv);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "insertFile is fail:" + e.getLocalizedMessage());
		}
		
		return row;
	}
	/**
	 * 
	 */
	@Override
	public void updateFile(FileInfoResponseV2 fileInfoResponse,boolean issync) {
		try {
			String where = id + "=? and "+ owner_by +"=?";
			String[] whereValue = {fileInfoResponse.getId() ,fileInfoResponse.getOwnerBy()};
			ContentValues cv = new ContentValues();
			cv.put(IBaseDao.id, fileInfoResponse.getId());
			cv.put(IBaseDao.file_name, fileInfoResponse.getName());
			cv.put(IBaseDao.is_file, 1);
			cv.put(IBaseDao.owner_by, fileInfoResponse.getOwnerBy());
			cv.put(IBaseDao.parent_folder_id, fileInfoResponse.getParent());
			cv.put(IBaseDao.file_md5, fileInfoResponse.getMd5());
			cv.put(IBaseDao.file_size, fileInfoResponse.getSize());
			cv.put(IBaseDao.server_ctime, fileInfoResponse.getCreatedAt());
			cv.put(IBaseDao.server_mtime, fileInfoResponse.getModifiedAt());
			cv.put(IBaseDao.local_path, "");
			cv.put(IBaseDao.client_ctime, fileInfoResponse.getContentCreatedAt());
			cv.put(IBaseDao.client_mtime, fileInfoResponse.getContentModifiedAt());
			cv.put(IBaseDao.static_status, fileInfoResponse.getStatus());
			cv.put(IBaseDao.trans_status, 0);
			cv.put(IBaseDao.trans_status_ref_cnt, 0);
			cv.put(IBaseDao.is_exist, 0);
			cv.put(IBaseDao.file_true_md5, "");
			cv.put(IBaseDao.local_operation_time, 5446456);
			cv.put(IBaseDao.local_last_modify_time, Calendar.getInstance().getTimeInMillis());
			cv.put(IBaseDao.file_sha1, fileInfoResponse.getSha1());
			cv.put(IBaseDao.isencrypt, fileInfoResponse.isEncrypt());
			cv.put(IBaseDao.isshare, fileInfoResponse.isShare());
			cv.put(IBaseDao.isshare_link, fileInfoResponse.isSharelink());
			if(issync){
				cv.put(IBaseDao.isSync, 0);
			}else{
				cv.put(IBaseDao.isSync, fileInfoResponse.isSync() ? 1 : 0);
			}
			cv.put(IBaseDao.fileIcon, fileInfoResponse.getThumbnailURL());
			this.getDb().update(TABLE_NAME, cv, where, whereValue);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "updateFile is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public void updateFile(FileInfo fileInfo) {

	}

	@Override
	public void inserOrUpdateFile(FileInfoResponseV2 fileInfo) {

	}

	@Override
	public List<FileInfo> getFileList(String folderId , String ownerBy) {
		List<FileInfo> fileInfoList = new ArrayList<FileInfo>();
		try {
			Cursor cursor = this.getDb().rawQuery("select * from " + TABLE_NAME + " where " + IBaseDao.parent_folder_id + " =? and "+owner_by+ "=?",
					new String[] { folderId , ownerBy});
			if (!cursor.moveToFirst()) {
				return fileInfoList;
			}
			do {
				FileInfo fileInfo = new FileInfo();
				fileInfo.fromCursor(cursor);
				fileInfoList.add(fileInfo);
			} while (cursor.moveToNext());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "getFileList is fail:" + e.getLocalizedMessage());
		}

		return fileInfoList;
	}

	@Override
	public FileInfo getFileById(String fileId,String ownerBy) {
		FileInfo fileInfo = null;
		try {
			if(null != fileId){
				Cursor cursor = this.getDb()
						.rawQuery("select * from " + TABLE_NAME + "  where "+id +" = ? and "+ owner_by +"=?", new String[] { fileId,ownerBy });
				if (cursor.moveToFirst()) {
					fileInfo = new FileInfo();
					fileInfo.fromCursor(cursor);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "getFileById is fail:" + e.getLocalizedMessage());
		}
		return fileInfo;
	}

	@Override
	public void deleteFile(String fileId,String ownerBy) {
		try {
			if(null != fileId){
				this.getDb().execSQL("delete from " + TABLE_NAME + " where id = ? and "+owner_by +"=?", new String[] { fileId, ownerBy});
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "deleteFile is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public void updateLocalPath(String fileId, String ownerBy ,String localPath) {
		try {
			if(null != fileId){
				this.getDb().execSQL("update  " + TABLE_NAME + " set " + IBaseDao.local_path + " = ? where id = ? and "+owner_by+"=?" ,
						new String[] { localPath, fileId ,ownerBy});
			}	
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "updateLocalPath is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public void updateTransStatus(int status, String fileId,String ownerBy) {
		try {
			if(null != fileId){
				String sql = "update " + TABLE_NAME + "  set " + IBaseDao.trans_status + " = " + status + " where id = " + fileId +" and owner_by = "+ownerBy;
				this.getDb().execSQL(sql);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "updateTransStatus is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public void updateSyncStatus(int syncStatus, String fileId,String ownerBy) {
		try {
			String where = id + "=? and "+owner_by+"=?";
			String[] whereValue = { fileId ,ownerBy};
			ContentValues cv = new ContentValues();
			cv.put(isSync, syncStatus);
			this.getDb().update(TABLE_NAME, cv, where, whereValue);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "updateSyncStatus is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public long getLastUpdateTime(String fileId) {
		long lastUpdateTime = 0;
		try {
			if(null != fileId){
				Cursor cursor = this.getDb().rawQuery("select * from  " + TABLE_NAME + " where id = ?",
						new String[] { fileId });
				if (cursor.moveToFirst()) {
					lastUpdateTime = cursor.getInt(cursor.getColumnIndex(IBaseDao.local_last_modify_time));
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "getLastUpdateTime is fail:" + e.getLocalizedMessage());
		}
		return lastUpdateTime;
	}

	@Override
	public void updateLastUpdateTime(String objectId) {
		try {
			if(null != objectId){
				this.getDb().execSQL("update  " + TABLE_NAME + " set " + IBaseDao.local_last_modify_time + "= ? where id = ?",
						new String[] { "" + Calendar.getInstance().getTimeInMillis(), objectId });
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "updateLastUpdateTime is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public void deleteAll() {
		// TODO Auto-generated method stub
		try {
			this.getDb().delete(TABLE_NAME, null, null);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "deleteAll is fail:" + e.getLocalizedMessage());
		}
	}

	@Override
	public List<FileInfo> getFileListPage(int flag, String folderId) {
		if(null != folderId){
			int number = ClientConfig.CLOUD_COUNT_PER_PAGE;
			int count = ShareDriveApplication.getInstance().getMyCloudDrivePage() * number;
			if (Constant.SHARED_GET_FILE_LIST_STATE == flag) {
				number = ClientConfig.SHARED_COUNT_PER_PAGE;//
				count = ShareDriveApplication.getInstance().getMySharePage() * number;
			}
			List<FileInfo> fileInfoList = new ArrayList<FileInfo>();
			try {
				Cursor cursor = this.getDb().rawQuery("select * from " + TABLE_NAME + " where " + IBaseDao.parent_folder_id + " = ? Order by server_mtime desc" +  " limit ?" +  " offset ?",
						new String[] { folderId, String.valueOf(number), String.valueOf(count) });
				if (!cursor.moveToFirst()) {
					return fileInfoList;
				}
				do {
					FileInfo fileInfo = new FileInfo();
					fileInfo.fromCursor(cursor);
					fileInfoList.add(fileInfo);
				} while (cursor.moveToNext());
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				LogUtil.e(LOG_TAG, "getFileListPage is fail:" + e.getLocalizedMessage());
			}
			
			return fileInfoList;
		}else{
			LogUtil.e(LOG_TAG,"folderId is null");
		}
		return null;
	}

	@Override
	public void cleanCatch(){
		try {
			String currentUser = ShareDriveApplication.getInstance().getWnerID();
			if(currentUser == null || currentUser.equals("")){
				return ;
			}
			ContentValues values = new ContentValues();
			values.put(IBaseDao.local_path, "");
			values.put(IBaseDao.trans_status, Constant.DOWNLOAD_NON_UPDATE_DB);
			values.put(IBaseDao.isSync, Constant.DOWNLOAD_STATUS_NOCACHE_DB);
			String whereClause = IBaseDao.owner_by + " = ?";
			String[] whereArgs = {currentUser};
			this.getDb().update(TABLE_NAME, values, whereClause, whereArgs);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(LOG_TAG, "deleteAll is fail:" + e.getLocalizedMessage());
		}
	}
}
